package com.leyou.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.dto.pojo.BrandDTO;
import com.leyou.dto.pojo.CategoryDTO;
import com.leyou.dto.pojo.SpecGroupDTO;
import com.leyou.dto.pojo.SpuDTO;
import com.leyou.item.client.ItemClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HeGuanChao
 * @Description TODO
 * @Date 2020/4/9 15:47
 */
@Slf4j
@Service
public class PageService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private SpringTemplateEngine templateEngine;
    @Value("${ly.static.itemDir}")
    private String itemDir;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    public Map<String, Object> loadItemData(Long id) {
        // 查询spu
        SpuDTO spuDTO = itemClient.querySpuById(id);
        // 查询分类
        List<CategoryDTO> categoryDTOList = itemClient.queryByIds(spuDTO.getCategoryIds());
        // 查询品牌
        BrandDTO brandDTO = itemClient.queryById(spuDTO.getBrandId());
        // 查询规格组
        List<SpecGroupDTO> specGroupDTOList = itemClient.querySpecsByCid(spuDTO.getCid3());

        Map<String, Object> data = new HashMap<>();
        data.put("brand", brandDTO);
        data.put("spuName", spuDTO.getName());
        data.put("subTitle", spuDTO.getSubTitle());
        data.put("skus", spuDTO.getSkus());
        data.put("detail", spuDTO.getSpuDetail());
        data.put("specs", specGroupDTOList);
        data.put("categories", categoryDTOList);
        return data;
    }

    /**
     * 页面静态化-创建item.html静态页面
     *
     * @param spuId 规格组id spuId
     */
    public void createItemHtml(Long spuId) {
        // 创建上下文
        Context context = new Context();
        // 为上下文设置数据
        context.setVariables(loadItemData(spuId));
        // 创建文件夹
        File fileDir = new File(itemDir);
        // 判断文件夹是否存在
        if (!fileDir.exists()) {
            // 判断文件夹是否创建成功
            if (!fileDir.mkdir()) {
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        // 创建文件
        File file = new File(fileDir, spuId + ".html");
        // 输出文件
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            templateEngine.process(itemTemplate, context, writer);
        } catch (Exception e) {
            log.error("【静态页服务】静态页生成失败，商品id：{}", spuId, e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    /**
     * 删除静态页面
     *
     * @param spuId
     */
    public void deleteItemHtml(Long spuId) {
        // 目标文件
        File file = new File(itemDir, spuId + ".html");
        // 删除文件
        if (file.exists()) {
            boolean delete = file.delete();
            if (!delete) {
                log.error("【静态化服务】静态页删除失败，商品id：{}", spuId);
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
